<template>
    <el-dialog title="批量导入线路" v-model="visible" width="500px">
        <el-form label-position="top">
            <el-form-item label="请选择 Excel 文件">
                <el-upload
                    drag
                    :action="uploadUrl"
                    :headers="headers"
                    :on-success="handleSuccess"
                    :before-upload="beforeUpload"
                    accept=".xlsx,.xls"
                    name="file"
                    :data="formData"
                >
                    <icon name="el-icon-UploadFilled" size="32" />
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                </el-upload>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>
<script lang="ts" setup>
import {computed, reactive, ref} from 'vue'
import feedback from '@/utils/feedback'
import useUserStore from '@/stores/modules/user'
import config from "@/config";
import useAppStore from "@/stores/modules/app";

const visible = ref(false)
const userStore = useUserStore()
const appStore = useAppStore()
const uploadUrl = ref(`${config.baseUrl}/${config.urlPrefix}/travel.line/import`)
const headers = computed(() => ({
  token: userStore.token,
  version: appStore.config.version
}))
const formData = reactive({
  travel_agency_id: 0,
  user_id:userStore.userInfo.id
})
// 打开弹窗方法
const open = (id: number) => {
  formData.travel_agency_id = id
  visible.value = true
}

// 上传成功回调
const handleSuccess = (res) => {
  if (res.code === 1) {
    feedback.msgSuccess("导入成功")
    visible.value = false
  } else {
    return feedback.msgError("导入失败")
  }
}

// 校验文件类型
const beforeUpload = (file) => {
  const isValid = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'].includes(file.type)
  if (!isValid) {
    return feedback.msgWarning("只能上传 Excel 文件")
  }
  return true
}

defineEmits(['success', 'close'])

defineExpose({open})
</script>
